﻿using BillingExceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

namespace Billing
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            _canIssueChangeData = false;
            try
            {
                LoadDataOnForm();
                comboBoxAutentificationType.SelectedIndexChanged += dataChanged;
            }
            finally
            {
                _canIssueChangeData = true;
                checkVisible();
            }
        }

        // Обработка нажатия кнопок меню
        private void tsbSave_Click(object sender, EventArgs e)
        {
            LoadDataToSettings();
            _isChanged = false;
            checkVisible();
        }
        private void tsbCancel_Click(object sender, EventArgs e)
        {
            LoadDataOnForm();
            _isChanged = false;
            checkVisible();
        }
        private void buttonTestConnection_Click(object sender, EventArgs e)
        {

        }
        private void tsbStartService_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                ServiceData.Check(BillingSettings.Item);
                ServiceControl.Item.StartService(new string[]
                    {
                        BillingSettings.Item.ServerName, 
                        BillingSettings.Item.DbName,
                        BillingSettings.Item.IsWindowsAuthentification.ToString(),
                        BillingSettings.Item.Login,
                        BillingSettings.Item.Password,
                        BillingSettings.Item.PathToCatalog,
                        BillingSettings.Item.PathToArchive,
                        BillingSettings.Item.Interval.ToString(),
                        BillingSettings.Item.IsArchived.ToString()
                    }
                );
                checkVisible();
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void tsbStopService_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor; 
            try
            {
                ServiceControl.Item.StopService();
                checkVisible();
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void btnCatalogOpen_Click(object sender, EventArgs e)
        {
            Control ctrl = sender as Control;
            if (ctrl != null)
            {
                DialogResult result = folderBrowserDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    switch (ctrl.Name)
                    {
                        case "btnCatalogOpen":
                            textBoxFilesCatalog.Text = folderBrowserDialog.SelectedPath;
                            break;
                        case "btnArchiveOpen":
                            textBoxArchive.Text = folderBrowserDialog.SelectedPath;
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        private void tsbHelp_Click(object sender, EventArgs e)
        {
            try
            {
                //System.Diagnostics.Process.Start(Common.HELP_PATH);
                Common.GetHelp("", HelpNavigator.TableOfContents);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
        private void FormMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                try
                {
                    //System.Diagnostics.Process.Start(Common.HELP_PATH);
                    Common.GetHelp("", HelpNavigator.TableOfContents);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
        }

        #region Helper

        private void checkVisible()
        {
            // Проверка возможности тестирования соединения
            bool b1 = string.IsNullOrEmpty(textBoxServer.Text) || string.IsNullOrEmpty(textBoxDb.Text) || string.IsNullOrEmpty(textBoxLogin.Text)
                || string.IsNullOrEmpty(textBoxPassword.Text) || string.IsNullOrEmpty(textBoxFilesCatalog.Text) || string.IsNullOrEmpty(textBoxArchive.Text)
                || _isChanged;
            // Проверяется, запущена ли служба
            bool b2 = ServiceControl.Item.ServiceStatus == System.ServiceProcess.ServiceControllerStatus.Running;

            tsbStartService.Enabled = !b1 && !b2;
            tsbStopService.Enabled = b2;
            tsbSave.Enabled = _isChanged;
            tsbCancel.Enabled = _isChanged;
            tssServiceStatus.Text = ServiceControl.Item.ServiceStatusCaption;
        }
        private void dataChanged(object sender, EventArgs e)
        {
            if (_canIssueChangeData)
            {
                _isChanged = true;
                checkVisible();
            }
        }
        private void LoadDataOnForm()
        {
            BillingSettings.Load();
            textBoxServer.Text = BillingSettings.Item.ServerName;
            textBoxDb.Text = BillingSettings.Item.DbName;
            textBoxLogin.Text = BillingSettings.Item.Login;
            textBoxPassword.Text = BillingSettings.Item.Password;
            textBoxFilesCatalog.Text = BillingSettings.Item.PathToCatalog;
            textBoxArchive.Text = BillingSettings.Item.PathToArchive;
            numericUpDownInterval.Value = BillingSettings.Item.Interval;
            checkBoxIsArchived.Checked = BillingSettings.Item.IsArchived;
            comboBoxAutentificationType.SelectedIndex = BillingSettings.Item.IsWindowsAuthentification ? 0 : 1;
        }
        private void LoadDataToSettings()
        {
            BillingSettings.Item.ServerName = textBoxServer.Text;
            BillingSettings.Item.DbName = textBoxDb.Text;
            BillingSettings.Item.Login = textBoxLogin.Text;
            BillingSettings.Item.Password = textBoxPassword.Text;
            BillingSettings.Item.PathToCatalog = textBoxFilesCatalog.Text;
            BillingSettings.Item.PathToArchive = textBoxArchive.Text;
            BillingSettings.Item.Interval = Convert.ToInt32(numericUpDownInterval.Value, CultureInfo.InvariantCulture);
            BillingSettings.Item.IsArchived = checkBoxIsArchived.Checked;
            BillingSettings.Item.IsWindowsAuthentification = comboBoxAutentificationType.SelectedIndex == 0;
            BillingSettings.Save();
        }
        private void comboBoxAutentificationType_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBoxLogin.Enabled = comboBoxAutentificationType.SelectedIndex == 1;
            textBoxPassword.Enabled = comboBoxAutentificationType.SelectedIndex == 1;
        }


        #endregion

        private bool _isChanged = false;
        private bool _canIssueChangeData = true;
    }
}
